const ForgetPasswordModel = require('../models/forgetPasswordModel')
const UserModel = require('../models/userModel')
const { DEFAULT_PASSWORD } = require('../project.config')

class ForgetPasswordController {
    static async findList (ctx) {
        let { page, size } = ctx.query
        page = Number(page)
        size = Number(size)

        const list = await ForgetPasswordModel.find({
            status: 1,
        }).skip((page - 1) * size).limit(size).exec()

        const total = await ForgetPasswordModel.countDocuments().exec()
        ctx.body = {
            code: 1,
            data: {
                list,
                total,
            },
        }
    }

    static async create (ctx) {
        const { account } = ctx.request.body
        // 账户必须存在
        const user = await UserModel.find({
            account,
        }).exec()
        // 不能重复申请重置密码
        const pwd = await ForgetPasswordModel.find({
            status: 1,
            account,
        }).exec()

        if (!user || !pwd) {
            ctx.body = {
                code: 0,
                msg: '账户不存在或重复提交申请',
            }
            return
        }

        const record = new ForgetPasswordModel({
            account,
            status: 1,
        })

        await record.save()
        ctx.body = {
            code: 1,
            msg: '申请成功',
        }
    }

    static async update (ctx) {
        const { id, status } = ctx.request.body
        const record = await ForgetPasswordModel.findOne({
            _id: id,
        })
        if (!record) {
            ctx.body = {
                code: 0,
                msg: '找不到这条数据的申请记录',
            }
            return
        }
        record.status = status

        if (status === 2) {
            const user = await UserModel.findOne({
                account: record.account,
            }).exec()
            if (user) {
                user.password = DEFAULT_PASSWORD
                await user.save()
            }
            ctx.body = {
                code: 1,
                msg: '密码已重置为123456',
            }
        } else {
            ctx.body = {
                code: 1,
                msg: '已忽略',
            }
        }
        await record.save()
    }
}

module.exports = ForgetPasswordController
